package com.jacky.sso.service;

import com.alibaba.fastjson.JSON;
import com.jacky.sso.domain.CustomerUser;
import com.jacky.sso.entities.SysPermission;
import com.jacky.sso.entities.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CustomerUserDetailsService implements UserDetailsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerUserDetailsService.class);

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private IUserService userService;
    @Resource
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.getByUsername(username);
        if (null == sysUser) {
            LOGGER.warn("用户{}不存在", username);
            throw new UsernameNotFoundException(username);
        }
        List<SysPermission> permissions = permissionService.findByUserId(sysUser.getId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissions)) {
            permissions.forEach(p -> authorities.add(new SimpleGrantedAuthority(p.getCode())));
        }
        CustomerUser user = new CustomerUser(sysUser.getUsername(), passwordEncoder.encode(sysUser.getPassword()), authorities);
        LOGGER.info("用户{}登录成功:{}", sysUser.getUsername(), JSON.toJSONString(user));
        return user;
    }
}
